<template>
  <div>
    <el-row>
      <classify-select v-model="form.classifyid" />
    </el-row>
    <el-form label-width="60px" :rules="rules" v-loading="loading" ref="form" :model="form">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称" maxlength="255" show-word-limit />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input type="number" v-model="form.price"><template slot="prepend">￥</template></el-input>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input v-model.number="form.stock" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <tags v-model="form.tags" />
      </el-form-item>
      <el-form-item label="封面" prop="image">
        <uploads v-model="form.image" @change="$refs.form.validateField('image')" />
      </el-form-item>
      <el-form-item label="规格" prop="specification">
        <tags v-model="form.specification" />
      </el-form-item>
      <el-form-item label="品牌" prop="brandid">
        <el-select filterable remote :remote-method="getBrandList" v-model="form.brandid" placeholder="搜索品牌">
          <el-option v-for="brand in brandList" :key="brand.id" :label="brand.name" :value="brand.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠" prop="discount">
        <el-input v-model.number="form.discount" maxlength="3">
          <template #prepend>
            <span class="discount-word"> {{ discountWord }} </span>
          </template>
          <template #append>
            <span> 折后价: ￥{{ favorablePrice }} </span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="center-text">
        <el-button type="success" @click="save">保存</el-button>
        <el-button v-if="form.id" type="warning" @click="init">恢复</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import ClassifySelect from '@/components/ClassifySelect.vue'
import { goodsFromid, goodsModify, goodsAdd } from '@/api/goods'
import { brandSearch } from '@/api/brand'
import uploads from '@/components/uploads.vue'
import Tags from '@/components/Tags.vue'

export default {
  components: {
    ClassifySelect,
    uploads,
    Tags,
  },
  data() {
    const tansy = (rule, /**@type {array} */ value, callback) => {
      value.forEach((item) => {
        if (/\s/.test(item) || item.length === 0) {
          return callback(new Error('标签不能为空或空格'))
        }
      })
      callback()
    }
    const names = (rule, /**@type {array} */ value, callback) => {
      if (/\s/.test(value) || value.length === 0) {
        return callback(new Error('用户名中不能有空格'))
      }
      callback()
    }
    const images = (rule, /**@type {array} */ value, callback) => {
      if (value.length <= 2) {
        return callback(new Error('图片不能少于3张'))
      }
      callback()
    }
    const discounters = (rule, /**@type {array} */ value, callback) => {
      if (value < 1 || value > 100) {
        return callback(new Error('优惠价格不能小于1或大于100'))
      }
      callback()
    }
    return {
      form: {
        id: undefined,
        classifyid: undefined,
        name: '',
        price: 0,
        stock: 0,
        tags: [],
        image: [],
        specification: [],
        brandid: undefined,
        discount: 100,
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 255, message: '长度在 3 到 5 个字符', trigger: 'blur' },
          { validator: names, trigger: 'blur' },
        ],
        price: [{ required: true, message: '请输入商品价格' }],
        stock: [
          { required: true, message: '请输入商品名称' },
          { type: 'number', message: '库存数量必须为数字值' },
        ],
        tags: [{ validator: tansy }],
        image: [{ validator: images }],
        specification: [{ validator: tansy }],
        brandid: [{ required: true, message: '请输入商品品牌', trigger: 'blur' }],
        discount: [{ type: 'number', message: '优惠必须为数字值' }, { validator: discounters }],
      },
      brandList: [],
      loading: false,
    }
  },
  computed: {
    favorablePrice() {
      const { discount, price } = this.form
      if (isNaN(+this.form.discount)) return '0.00'
      return ((discount * price) / 100).toFixed(2)
    },
    discountWord() {
      if (this.form.discount > 100) this.form.discount = 100
      if (this.form.discount < 1) return '输入正确的值'
      if (isNaN(+this.form.discount)) return '输入正确的值'
      const { discount } = this.form
      if (discount === 100) return '不打折'
      const smp = '零一二三四五六七八九'
      const g1 = smp[parseInt((discount / 10) % 10)]
      const g2 = smp[parseInt(discount % 10)]
      return g1 + (g2 === '零' ? '' : g2) + '折'
    },
  },
  methods: {
    /**初始化 */
    async init() {
      const { id } = this.query
      if (id === 'new') return
      this.loading = true
      const data = await goodsFromid({ id })
      if (data.code === 431) return this.$router.replace({ name: '404' })
      if (data.code !== 200) return this.$message.error('获取商品详情失败,错误码:' + data.code)
      this.loading = false
      this.form = data.data
      this.brandList.push({ ...this.form.brand })
    },
    /**获取品牌列表 */
    async getBrandList(qw) {
      const data = await brandSearch({ qw })
      if (data.code !== 200) return this.methods.error('获取匹配列表失败,错误码:' + data.code)
      this.brandList = data.data
    },
    /**取消 */
    cancel() {
      this.$router.push({ name: 'goods-exhibit' })
    },
    /**保存 */
    async save() {
      this.$refs.form
        .validate()
        .then(async () => {
          if (!this.form.classifyid) return this.$message.error('保存失败,请选择分类')
          const data = this.form.id ? await goodsModify(this.form) : await goodsAdd(this.form)
          if (data.code !== 200) return this.$message.error('保存失败,稍后重试,错误码:' + data.code)
          this.$message.success('保存成功')
          this.$router.push({ name: 'goods-exhibit' })
        })
        .catch(() => {})
    },
  },
  watch: {
    '$route.params': {
      immediate: true,
      deep: true,
      handler(value) {
        console.log(value)
        this.query = { ...value }
        this.init()
      },
    },
  },
}
</script>

<style lang="scss" scoped>
.discount-word {
  display: inline-block;
  width: 80px;
}
</style>
